package com.mrli.cat.weather.database;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.util.Log;

import com.mrli.cat.weather.activity.ForecastFragment;
import com.mrli.cat.weather.activity.WeatherPreferenceActivity;
import com.mrli.cat.weather.tools.Constant;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by MrLi on 2015/6/25.
 * 向UI提供数据
 */
public class WeatherProvider extends ContentProvider {
    private static final int WEATHER = 100;
    private static final int LOCATION = 200;
    private static final int WEATHER_WITH_CITY_NAME = 300;
    private static final int CITY = 400;
    private WeatherDbHelper mOpenHelper;
    public static final String CITY_DATABASE_NAME = "city.db";

    private static final UriMatcher sUriMatcher = buildUriMatcher();

    private static UriMatcher buildUriMatcher() {
        final UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);
        matcher.addURI(WeatherContract.AUTHORITY, WeatherContract.LocationEntry.TABLE_NAME, LOCATION);
        matcher.addURI(WeatherContract.AUTHORITY, WeatherContract.WeatherEntry.TABLE_NAME, WEATHER);
        matcher.addURI(WeatherContract.AUTHORITY, WeatherContract.WeatherEntry.TABLE_NAME + "/cityName" + "/*", WEATHER_WITH_CITY_NAME);
        matcher.addURI(WeatherContract.AUTHORITY, WeatherContract.CityEntry.TABLE_NAME, CITY);
        return matcher;
    }

    @Override
    public boolean onCreate() {
        mOpenHelper = new WeatherDbHelper(getContext());
        return true;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
        Cursor retCursor;
        final int match = sUriMatcher.match(uri);
        switch (match) {
            //查询当指定城市的所有天气信息
            case WEATHER_WITH_CITY_NAME: {
            //读取显示的行数
                SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());
                int lines = sharedPreferences.getInt(WeatherPreferenceActivity.FORECAST_DAY, Constant.OpenWeatherMap.MAX_FORECAST_DAY);
                StringBuffer buffer = new StringBuffer();
                buffer.append("select "
                                + WeatherContract.WeatherEntry.TABLE_NAME + "."
                                + WeatherContract.WeatherEntry._ID + ", "
                                + WeatherContract.WeatherEntry.TABLE_NAME + "."
                                + WeatherContract.WeatherEntry.COLUMN_WEATHER + ", "
                                + WeatherContract.WeatherEntry.TABLE_NAME + "."
                                + WeatherContract.WeatherEntry.COLUMN_TIME + ", "
                                + WeatherContract.WeatherEntry.TABLE_NAME + "."
                                + WeatherContract.WeatherEntry.COLUMN_TEMP_MAX + ", "
                                + WeatherContract.WeatherEntry.TABLE_NAME + "."
                                + WeatherContract.WeatherEntry.COLUMN_TEMP_MIN
                                + " from " + WeatherContract.WeatherEntry.TABLE_NAME
                                + " inner join " + WeatherContract.LocationEntry.TABLE_NAME
                                + " on(" + WeatherContract.WeatherEntry.TABLE_NAME + "."
                                + WeatherContract.WeatherEntry.COLUMN_CITY_ID + "="
                                + WeatherContract.LocationEntry.TABLE_NAME + "."
                                + WeatherContract.LocationEntry._ID + ")"
                                + "where " + WeatherContract.LocationEntry.TABLE_NAME + "."
                                + WeatherContract.LocationEntry.COLUMN_NAME + "= ?"
                                + " order by " + WeatherContract.WeatherEntry.TABLE_NAME + "."
                                + WeatherContract.WeatherEntry.COLUMN_TIME + " asc"
                                + " limit " + lines
                );
                //获取Uri中的城市名称
                List<String> pathSegment = uri.getPathSegments();
                String cityName = pathSegment.get(2);
                if (cityName.equals("error")) {
                    retCursor = mOpenHelper.getReadableDatabase().rawQuery(buffer.toString(), new String[]{cityName});
                } else {
                    retCursor = mOpenHelper.getReadableDatabase().rawQuery(buffer.toString(), new String[]{cityName});
                }
            }
            break;
            //查询数据库中Location表
            case LOCATION: {
                retCursor = mOpenHelper.getReadableDatabase().query(
                        WeatherContract.LocationEntry.TABLE_NAME,
                        projection,
                        selection,
                        selectionArgs,
                        null,
                        null,
                        sortOrder
                );
            }
            break;
            //查询数据库中的Weather表
            case WEATHER: {
                retCursor = mOpenHelper.getReadableDatabase().query(
                        WeatherContract.WeatherEntry.TABLE_NAME,
                        projection,
                        selection,
                        selectionArgs,
                        null,
                        null,
                        sortOrder
                );
            }
            break;
            //查询默认的城市列表
            case CITY: {
                SQLiteDatabase cityDataBase = SQLiteDatabase.openDatabase(getContext().getFilesDir().getPath() + "/" + CITY_DATABASE_NAME, null, SQLiteDatabase.OPEN_READONLY);
                retCursor = cityDataBase.query(
                        WeatherContract.CityEntry.TABLE_NAME,
                        projection,
                        selection,
                        selectionArgs,
                        null,
                        null,
                        sortOrder
                );
            }
            break;
            default:
                throw new UnsupportedOperationException("未知的Uri: " + uri);
        }
        retCursor.setNotificationUri(getContext().getContentResolver(), uri);
        return retCursor;
    }

    @Override
    public String getType(Uri uri) {
        final int match = sUriMatcher.match(uri);
        switch (match) {
            case WEATHER:
                return WeatherContract.WeatherEntry.CONTENT_TYPE;
            case WEATHER_WITH_CITY_NAME:
                return WeatherContract.WeatherEntry.CONTENT_TYPE;
            case LOCATION:
                return WeatherContract.LocationEntry.CONTENT_TYPE;
            case CITY:
                return WeatherContract.CityEntry.CONTENT_ITEM_TYPE;
            default:
                throw new UnsupportedOperationException("未知的Uri" + uri);
        }
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
        final int match = sUriMatcher.match(uri);
        switch (match) {
            case WEATHER: {
                long _id = db.insert(WeatherContract.WeatherEntry.TABLE_NAME, null, values);
                if (_id > 0) {
                    getContext().getContentResolver().notifyChange(uri, null);
                }
            }
            break;
            case LOCATION: {
                long _id = db.insert(WeatherContract.LocationEntry.TABLE_NAME, null, values);
                if (_id > 0) {
                    getContext().getContentResolver().notifyChange(uri, null);
                }
            }
            break;
        }
        return null;
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        final int match = sUriMatcher.match(uri);
        final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
        int number = 0;
        switch (match) {
            case LOCATION: {
                number = db.delete(WeatherContract.LocationEntry.TABLE_NAME, selection, selectionArgs);
            }
            break;
            case WEATHER: {
                number = db.delete(WeatherContract.WeatherEntry.TABLE_NAME, selection, selectionArgs);
            }
            break;
        }
        return number;
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
        final int match = sUriMatcher.match(uri);
        final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
        int number = 0;
        switch (match) {
            case LOCATION: {
                number = db.update(WeatherContract.LocationEntry.TABLE_NAME, values, selection, selectionArgs);
            }
            break;
            case WEATHER: {
                number = db.update(WeatherContract.WeatherEntry.TABLE_NAME, values, selection, selectionArgs);
            }
            break;
        }
        getContext().getContentResolver().notifyChange(uri, null);
        return number;
    }

    //插入多行数据到数据库
    @Override
    public int bulkInsert(Uri uri, ContentValues[] values) {
        final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
        final int match = sUriMatcher.match(uri);
        List<Long> count = new ArrayList<Long>();
        switch (match) {
            case WEATHER: {
                long retID;
                for (ContentValues value : values) {
                    retID = db.insert(WeatherContract.WeatherEntry.TABLE_NAME, null, value);
                    if (retID != -1) {
                        count.add(retID);
                    }
                }
            }
            break;
        }
        if (count.size() > 0) {
            getContext().getContentResolver().notifyChange(uri, null);
        }
        return count.size();
    }
}
